﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using Tycho.Compiler;
using Tycho.Language;
using Tycho.Runtime;

namespace Tycho.Modules {
    public class HttpModuleLoader : IModuleLoader {
        private string BaseUrl;
        private AnyObject ModuleFrame;

        public HttpModuleLoader (string baseUrl, AnyObject moduleFrame) {
            if (!baseUrl.EndsWith ("/")) {
                baseUrl += "/";
            }
            BaseUrl = baseUrl;
            ModuleFrame = moduleFrame;
        }

        public Namespace BaseNamespace {
            get { return Namespaces.Root.GetNamespace ("world"); }
        }

        public AnyObject LoadModule (Namespace ns, IModuleScopeLoader moduleLoader) {
            ExpressionLanguage language = new ExpressionLanguage (TopLevel.RuntimeAssemblyModule, ns);

            string url = BaseUrl + String.Join ("/", ns.Path) + ".tycho";
            string source = new WebClient ().DownloadString (url);

            return language.LoadModule (source, url, ns, ModuleFrame, moduleLoader);
        }
    }
}
